const express = require('express');
const cors = require('cors');
const { testConnection, initDatabase } = require('./database/connection');
const matchesRouter = require('./routes/matches');

const app = express();
const PORT = process.env.PORT || 3000;

// 中间件配置
app.use(cors({
  origin: ['http://localhost:3000', 'http://localhost:5173', 'http://127.0.0.1:5173'],
  credentials: true
}));

app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true }));

// 请求日志中间件
app.use((req, res, next) => {
  console.log(`${new Date().toISOString()} - ${req.method} ${req.path}`);
  next();
});

// 健康检查接口
app.get('/health', (req, res) => {
  res.json({
    success: true,
    message: '服务运行正常',
    timestamp: new Date().toISOString()
  });
});

// API 路由
app.use('/api/matches', matchesRouter);

// 根路径
app.get('/', (req, res) => {
  res.json({
    success: true,
    message: '赛事数据API服务',
    version: '1.0.0',
    endpoints: {
      health: '/health',
      matches: {
        list: 'GET /api/matches/list',
        detail: 'GET /api/matches/:id',
        create: 'POST /api/matches',
        update: 'PUT /api/matches/:id',
        delete: 'DELETE /api/matches/:id'
      }
    }
  });
});

// 404 处理
app.use('*', (req, res) => {
  res.status(404).json({
    success: false,
    message: '接口不存在',
    path: req.originalUrl
  });
});

// 错误处理中间件
app.use((error, req, res, next) => {
  console.error('服务器错误:', error);
  res.status(500).json({
    success: false,
    message: '服务器内部错误',
    error: process.env.NODE_ENV === 'development' ? error.message : '未知错误'
  });
});

// 启动服务器
async function startServer() {
  try {
    // 测试数据库连接
    const dbConnected = await testConnection();
    if (!dbConnected) {
      console.error('❌ 无法连接到数据库，请检查配置');
      process.exit(1);
    }
    
    // 初始化数据库
    const dbInitialized = await initDatabase();
    if (!dbInitialized) {
      console.error('❌ 数据库初始化失败');
      process.exit(1);
    }
    
    // 启动服务器
    app.listen(PORT, () => {
      console.log('🚀 服务器启动成功!');
      console.log(`📍 服务地址: http://localhost:${PORT}`);
      console.log(`📊 API文档: http://localhost:${PORT}`);
      console.log(`🔍 健康检查: http://localhost:${PORT}/health`);
      console.log(`📋 赛事列表: http://localhost:${PORT}/api/matches/list`);
    });
    
  } catch (error) {
    console.error('❌ 服务器启动失败:', error);
    process.exit(1);
  }
}

// 优雅关闭
process.on('SIGINT', () => {
  console.log('\n🛑 正在关闭服务器...');
  process.exit(0);
});

process.on('SIGTERM', () => {
  console.log('\n🛑 正在关闭服务器...');
  process.exit(0);
});

startServer();
